package com.apexcode.common.security.service;

//  Ctrl + Alt + M 提取成公共代码

import cn.hutool.core.lang.UUID;

import com.apexcode.common.core.constants.CacheConstants;
import com.apexcode.common.core.constants.JwtConstants;
import com.apexcode.common.core.utils.JwtUtils;
import com.apexcode.common.redis.service.RedisService;
import com.apexcode.common.core.domain.LoginUser;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 */
@Component
@Slf4j
public class TokenService {

    @Autowired
    private RedisService redisService;


    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private final static long expireTime = CacheConstants.EXPIRATION;

    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    private final static Long MILLIS_MINUTE_TEN = CacheConstants.REFRESH_TIME * MILLIS_MINUTE;

    /**
     * 创建令牌
     */
    public String createToken(Long userId, String secret, Integer identity, String nickName, String headImage) {
        Map<String, Object> claims = new HashMap<>();
        String userKey = UUID.fastUUID().toString();
        claims.put(JwtConstants.LOGIN_USER_ID, userId);
        claims.put(JwtConstants.LOGIN_USER_KEY, userKey);
        String token = JwtUtils.createToken(claims, secret);
        String tokenKey = getTokenKey(userKey);
//            String tokenKey = "logintoken:" + sysUser.getUserId();
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser, CacheConstants.EXPIRATION, TimeUnit.MINUTES);

        return token;
    }

    public String createToken(Long userId, String secret, Integer identity, String nickName) {
        Map<String, Object> claims = new HashMap<>();
        String userKey = UUID.fastUUID().toString();
        claims.put(JwtConstants.LOGIN_USER_ID, userId);
        claims.put(JwtConstants.LOGIN_USER_KEY, userKey);
        String token = JwtUtils.createToken(claims, secret);

        // 身份认证具体还要存储那些信息 redis 表明用户身份字段 identity 1 表示普通用户 2 表示管理员用户
        // key 必须保证唯一
        // 使用什么样的数据结构 String key value
        String key = getTokenKey(userKey);
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        redisService.setCacheObject(key, loginUser, CacheConstants.EXPIRATION, TimeUnit.MINUTES);

        return token;
    }

    public void extendToken(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); // 获取令牌中的信息，解析payload中的信息，存储着用户唯一标识信息
            if (claims == null) {
                log.error("解析token: {}, 出现异常", token);
                return;
            }
        } catch (Exception e) {
            log.error("解析token: {}, 出现异常", token, e);
            return;
        }
        String userKey = JwtUtils.getUserKey(claims); // 获取jwt中的key
        String tokenkey = getTokenKey(userKey);
        System.out.println("延长的key是:"+tokenkey);

//        延长过期时间
        Long expire = redisService.getExpire(tokenkey, TimeUnit.MINUTES);
        if (expire != null && expire < CacheConstants.REFRESH_TIME ){
            redisService.expire(tokenkey,CacheConstants.EXPIRATION,TimeUnit.MINUTES);
        }
    }

    public LoginUser getLoginUser(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return null;
        }
        return redisService.getCacheObject(getTokenKey(userKey), LoginUser.class);
    }


    public boolean deleteLoginUser(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return false;
        }
        return redisService.deleteObject(getTokenKey(userKey));
    }

    public Long getUserId(Claims claims) {
        if (claims == null) return null;
        return Long.valueOf(JwtUtils.getUserId(claims));  //获取jwt中的key
    }

    public Long getUserId(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息  解析payload中信息  存储着用户唯一标识信息
            if (claims == null) {
                log.error("解析token：{}, 出现异常", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token：{}, 出现异常", token, e);
            return null;
        }
        return Long.valueOf(JwtUtils.getUserId(claims));  //获取jwt中的key
    }




    public String getUserKey(Claims claims) {
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);  //获取jwt中的key
    }

    private String getUserKey(String token, String secret) {
        Claims claims = getClaims(token, secret);

        if (claims == null) {
            return null;
        }
        return JwtUtils.getUserKey(claims);  //获取jwt中的key
    }

    public Claims getClaims(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息  解析payload中信息  存储着用户唯一标识信息
            if (claims == null) {
                log.error("解析token：{}, 出现异常", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token：{}, 出现异常", token, e);
            return null;
        }
        return claims;
    }

    public void refreshLoginUser(String nickName, String headImage, String userKey) {
        String tokenKey = getTokenKey(userKey);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser);
    }

    private String getTokenKey(String userKey) {
        return CacheConstants.LOGIN_TOKEN_KEY + userKey;
    }

}